package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static com.hmdp.content.RedisConstants.ICR_KEY;

@Component
public class RedisIdWorker {
    private static final Long BEGIN_TIMESTART =  1640995200L ;

    /**
     * 时间戳左移流出来的位置
     */
    private static final int COUNT_BITS = 32 ;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public Long nextId(String keyPrefix){

        //生成时间戳
        LocalDateTime nowTime = LocalDateTime.now();
        long nowSecond = nowTime.toEpochSecond(ZoneOffset.UTC);
        Long timeTap = nowSecond - BEGIN_TIMESTART;
        //生成序列号
        //获取当前日期，以时间拼接到key里去
        String dayKey = nowTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment(ICR_KEY + keyPrefix+":"+dayKey+":");

        //拼接并返回
        return timeTap <<COUNT_BITS | count;
    }
//
//    public static void main(String[] args){
//        LocalDateTime time = LocalDateTime.of(2022,1,1,0,0,0);
//        long second = time.toEpochSecond(ZoneOffset.UTC);
//        System.out.println("second:"+second);
//    }
}
